package com.app.teaware.goods;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.BasisBean;
import com.app.teaware.bean.CompanyListBean;
import com.app.teaware.bean.CraftListBean;
import com.app.teaware.bean.GoodsListBean;
import com.app.teaware.bean.GoodsListData;
import com.app.teaware.bean.GoodsSubmitData;
import com.app.teaware.bean.GoodsWorkm;
import com.app.teaware.bean.GoodsWorks;
import com.app.teaware.bean.GoodsWorksListBean;
import com.app.teaware.bean.LocationListBean;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.TrayInfoListBean;
import com.app.teaware.bean.UnitListBean;
import com.app.teaware.bean.UnitWholeListBean;
import com.app.teaware.bean.WorkListData;
import com.app.teaware.bluetooth.SearchBlueToothActivity;
import com.app.teaware.greendao.GreenDaoUtils;
import com.app.teaware.util.Analysis;
import com.app.teaware.util.BluetoothUtils;
import com.app.teaware.util.MyEvent;
import com.app.teaware.util.MyUtils;
import com.app.teaware.util.ReceiverUtils;
import com.app.teaware.util.UHFUtil;
import com.app.teaware.util.UnitUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.google.gson.Gson;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.MathUtils;
import my.TimeUtils;
import my.ViewUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/***
 * 领料管理-修改
 * **/
public class AddOrEditGoodsActivity extends BasisActivity {


//    @BindView(R.id.view_switch)
//    View view_switch;
//    @BindView(R.id.switch_out)
//    SwitchButton switch_out;

    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    MyAdapterList mAdapter;


    Calendar calendar;

    @BindView(R.id.text_time)
    TextView text_time;
    @BindView(R.id.text_type)
    TextView text_type;
    @BindView(R.id.text_craft)
    TextView text_craft;
    @BindView(R.id.edit_gno)
    EditText edit_gno;
    @BindView(R.id.edit_no)
    EditText edit_no;
    @BindView(R.id.view_customer)
    View view_customer;
    @BindView(R.id.view_tooth_weight)
    View view_tooth_weight;
    @BindView(R.id.text_customer)
    TextView text_customer;
    @BindView(R.id.text_tooth_weight)
    TextView text_tooth_weight;
    @BindView(R.id.text_location)
    TextView text_location;

    @BindView(R.id.text_weight)
    TextView text_weight;
    @BindView(R.id.edit_num)
    EditText edit_num;
    @BindView(R.id.edit_gwt)
    EditText edit_gwt;
    @BindView(R.id.text_total)
    TextView text_total;
    @BindView(R.id.text_good_name)
    TextView text_good_name;    //  货品名称
    @BindView(R.id.edit_status)
    EditText edit_status;
    @BindView(R.id.view_maker)
    View view_maker;
    @BindView(R.id.edit_maker)
    EditText edit_maker;
    @BindView(R.id.view_wbx)
    View view_wbx;
    @BindView(R.id.edit_wbx)
    EditText edit_wbx;
    @BindView(R.id.text_unit)
    TextView text_unit;


    @BindView(R.id.view_scan)
    View view_scan;
    @BindView(R.id.view_craft)
    View view_craft;
    @BindView(R.id.view_jgrk)
    View view_jgrk;     //加工入库才需要显示
    String craftCid;

    GoodsSubmitData submitData;
    GoodsWorkm workm;

    String[] types = null;
    String[] customers = null;
    CompanyListBean customerListbean;
    CraftListBean craftList;

    WorkListData workListData;    //如果是点击修改进来的  就会带值
    String title;

//    BoxInfoListBean boxListBean = null;     //纸箱信息
    TrayInfoListBean trayListBean = null;   //托盘信息
    UnitWholeListBean unitListBean = null;   //所有货品单位
    LocationListBean locationListBean = null;   //所有楼层


    //ice 硬件相关，rfid读卡成功通知
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case Constants.ACTION_UHF_RESULT_SEND:
                    Parcelable[] tagInfos = intent.getParcelableArrayExtra(Constants.EXTRA_TAG_INFO);
                    String qrcode = UHFUtil.getEPCId(tagInfos).trim().toUpperCase(Locale.ROOT);

                    switch (MyUtils.getHomeSelectName()){
                        case "加工入库":
                            if(goodsData == null) {
                                showToast("请先选择货品名称！");
                                return;
                            }
                            if(TextUtils.isEmpty(edit_num.getText().toString())) {
                                showToast("请先填写包装数量！");
                                return;
                            }
                            if(TextUtils.isEmpty(edit_gwt.getText().toString())) {
                                showToast("请先填写重量！");
                                return;
                            }

                            if(!TextUtils.isEmpty(qrcode)) {
                                newGoodsWorks(qrcode);
                            }
                            break;
                        default:
                            if(!TextUtils.isEmpty(qrcode)) {
                                getGoodsDataByEpcId(qrcode);
                            }

                            break;
                    }


                    break;
                case Constants.ACTION_SCANNER_RESULT_SEND:
                    final  String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
                    final  String scanResult_2 = intent.getStringExtra("SCAN_BARCODE2");
                    final  int barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE",-1);
                    final String scanStatus = intent.getStringExtra("SCAN_STATE");
                    if("ok".equals(scanStatus)) {
                        edit_gno.setText(scanResult_1.trim());
                    }
                    break;
            }
        }//end onReceiver
    };


    private void newGoodsWorks(String rfid){
        ArrayList<GoodsWorks> worksList = new ArrayList<>();
        GoodsWorks work = new GoodsWorks();
        work.setBfs(MyUtils.getHomeSelectId());            //1工单/2领料/3退料/4入库
        work.setGna(goodsData.getGna());       //货品名称
        work.setGno(goodsData.getGno());       //货品编码
        work.setGun(text_unit.getText().toString());       //整件单位
        work.setGunp(goodsData.getGunp());
        work.setGnu(edit_num.getText().toString());       //包装数量
        work.setRfid(rfid);
        work.setGid(goodsData.getGid());              //货品资料的id
        work.setBwf(""+GreenDaoUtils.getBoxListBean().getBwf());           //纸箱净重
        work.setGwtp(""+goodsData.getGwt());
        //注意auto放最后  需要其他数据
        work.setGwt(edit_gwt.getText().toString());  //重量
        work.autoSetGsp(goodsData.getGun(),goodsData.getDsn());      //货品规格
        work.setSid(goodsData.getSid());     // 半成品或者成品的type id
        work.setTid(goodsData.getSid());     // 半成品或者成品的type id
        worksList.add(work);
        submitListAddBean(worksList);
    }

    private boolean httpIsFinish = true;
    private void getGoodsDataByEpcId(String rfid){
        if(!httpIsFinish) return;
        httpIsFinish = false;
        if(TextUtils.isEmpty(rfid)) return;

        showLoading();
        MyParams params = new MyParams();
        params.put("aid", LoginBean.getInstance().getAcode());
        params.put("rfid",rfid);
        MyHttpUtils.get(Constants.URL_WORK_SELECT_BY_RFID, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        GoodsListBean listBean = (GoodsListBean) result;
                        if(listBean != null && listBean.getList().size()>0){
                            GoodsListData  data = listBean.getList().get(0);
                            ArrayList<GoodsWorks> worksList = new ArrayList<>();
                            GoodsWorks work = new GoodsWorks();
                            work.setBfs(MyUtils.getHomeSelectId());            //1工单/2领料/3退料/4入库
                            work.setGna(data.getGna());       //货品名称
                            work.setGno(data.getGno());       //货品编码
                            work.setGun(data.getGun());       //整件单位
                            work.setGunp(data.getGunp());       //最小单位
                            work.setGnu(data.getGnu());       //包装数量
                            work.setRfid(data.getRfid());
                            work.setGid(data.getGid());              //货品资料的id
                            work.setBwf(""+GreenDaoUtils.getBoxListBean().getBwf());           //纸箱净重
                            work.setGwtp(""+data.getGwtp());
                            //注意auto放最后  需要其他数据
                            work.setGsp(data.getGsp());      //货品规格
                            work.setGwt(data.getGwt());                  //重量
                            work.setSid(data.getSid());     // 半成品或者成品的type id
                            worksList.add(work);
                            submitListAddBean(worksList);
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        httpIsFinish = true;
                        hideLoading();
                    }
                },
                0, GoodsListBean.class);

    }

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.add_edit_goods_activity);
        setTitleLeftButton(null);
        submitData = new GoodsSubmitData();
        workm = new GoodsWorkm();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        checkBlueTooth();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        workListData = (WorkListData) getIntent().getSerializableExtra("bean");
        title = getIntent().getStringExtra("title");
        setTitle(title);
        if(title.equals("修改") && workListData == null){
            finish();
            return;
        }
        init();
        EventBus.getDefault().register(this);
    }



    void init(){
        trayListBean = GreenDaoUtils.getTrayListBean();  //托盘
//        System.out.println("ice boxinfo 托盘：毛重 = " + String.valueOf(stockListBean.getBwf()) + "，净重 = "  + String.valueOf(stockListBean.getBwt()));
//        boxListBean = GreenDaoUtils.getBoxListBean();  //纸箱
//        System.out.println("ice boxinfo 纸箱：毛重 = " + String.valueOf(boxListBean.getBwf()) + "，净重 = "  + String.valueOf(boxListBean.getBwt()));
        craftList = GreenDaoUtils.getCraftListBean();  //工艺
        unitListBean = GreenDaoUtils.getUnitWholeListBean();//整件单位
        locationListBean = GreenDaoUtils.getLocationListBean();//楼层


        MyParams params = null;

        switch (MyUtils.getHomeSelectName()){
            case "加工入库":
                types = getResources().getStringArray(R.array.order_type);
                view_customer.setVisibility(View.VISIBLE);
                view_jgrk.setVisibility(View.VISIBLE);
                view_tooth_weight.setVisibility(View.GONE);
                customerListbean = GreenDaoUtils.getCustomerListBean();
                break;
//            case "领料管理":
//                view_switch.setVisibility(View.VISIBLE);
//            case "退料管理":
            default:
                types = getResources().getStringArray(R.array.good_type);
                view_customer.setVisibility(View.GONE);
                break;
        }


        switch (title){
            case "修改":
                text_time.setText(workListData.getMdt());
                edit_no.setText(workListData.getMno());
                edit_gno.setText(workListData.getWno());
                edit_status.setText(workListData.getTys());
                edit_maker.setText(workListData.getUno());
                text_type.setText(workListData.getMty());
                text_location.setText(workListData.getLoc());
                text_customer.setText(workListData.getMna());
                text_craft.setText(workListData.getCna());
                craftCid = workListData.getCid();
//                switch_out.setChecked(workListData.getMfs()==1?true:false);
//            text_tooth_weight.setText(workListData.getWch());   //TODO 反正都要重新获取一遍

                showLoading();
                params = new MyParams();
                params.put("aid", LoginBean.getInstance().getAcode());
                params.put("tid", workListData.getMid());
                params.put("bfs", MyUtils.getHomeSelectId());
                MyHttpUtils.get(Constants.URL_WORK_GET_WORKS_BY_ID, params, new MyHttpListener() {
                            @Override
                            public void onSuccess(int httpWhat, Object result) {
                                if(isFinishing()) return;
                                GoodsWorksListBean listBean = (GoodsWorksListBean) result;
                                if(listBean.getList()!= null && listBean.getList().size()>0){
                                    mRecyclerView.setVisibility(View.VISIBLE);
                                    submitData.setWorks(listBean.getList());
                                }
                            }

                            @Override
                            public void onFailure(int httpWhat, Object result) {
                                super.onFailure(httpWhat, result);

                            }

                            @Override
                            public void onFinish(int httpWhat) {
                                setListView();
                                hideLoading();
                            }
                        },
                        0, GoodsWorksListBean.class);
                break;
            case "新增":
                MyUtils.setNotNullText(text_type,types[0]);
                viewShowOrHide();
                text_time.setText(TimeUtils.getCurrentTimeByFormat("yyyy-MM-dd"));
                view_maker.setVisibility(View.GONE);
                showLoading();

                //获取单号
                params = new MyParams();
                params.put("aid", LoginBean.getInstance().getAcode());
                MyHttpUtils.get(Constants.URL_WORK_RERURN_BO_BY_ID, params, new MyHttpListener() {
                            @Override
                            public void onSuccess(int httpWhat, Object result) {
                                if(isFinishing()) return;
                                BasisBean listBean = (BasisBean) result;
                                if(listBean.getResultData()!= null){
                                    edit_no.setText(listBean.getResultData());
                                }
                            }

                            @Override
                            public void onFailure(int httpWhat, Object result) {
                                super.onFailure(httpWhat, result);

                            }

                            @Override
                            public void onFinish(int httpWhat) {
                                hideLoading();
                            }
                        },
                        0, BasisBean.class);


                if(craftList.getAllNames()!=null){
                    MyUtils.setNotNullText(text_craft,craftList.getAllNames()[0]);
                    craftCid = craftList.getList().get(0).getCid();
                }
                if(unitListBean != null){
                    MyUtils.setNotNullText(text_unit,unitListBean.getList().get(0).getSna());
                }
                if(locationListBean != null){
                    MyUtils.setNotNullText(text_location,locationListBean.getList().get(0).getSna());
                }

                break;
        }

    }

    private void initDataByWorks(){
        if(submitData.getWorks() == null || submitData.getWorks().size()<1){
            text_weight.setText("");
            text_total.setText("");
            view_wbx.setVisibility(View.GONE);
        } else {
            if(trayListBean != null) {
                text_weight.setText(MathUtils.add(submitData.getAllBwt(),trayListBean.getBwt()));
                text_total.setText("" + submitData.getWorks().size());
                if (!MyUtils.getHomeSelectName().equals("加工入库")) {
                    edit_wbx.setText(submitData.getAllBwf());
                    //view_wbx.setVisibility(View.VISIBLE);
                    //text_unit.setVisibility(View.VISIBLE);
                }
            } else{
                showToast("ice 货品重量：当前无包装箱信息");
            }
        }
    }

    @OnClick({R.id.view_type,R.id.view_customer,R.id.view_craft,
            R.id.view_time,R.id.btn_add,R.id.btn_submit,
            R.id.view_tooth_weight,R.id.view_price,R.id.view_good_name,
            R.id.view_location,R.id.view_delete_all
    })
    public void btnLister(View v){
        switch (v.getId()){
            case R.id.view_delete_all:
                submitData.getWorks().clear();
                setListView();
                break;
            case R.id.view_type:
                if(types == null) return;
                new QMUIDialog.MenuDialogBuilder(mContext)
                        .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                        .addItems(types, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                        showToast("你选择了 " + types[which]);
                                text_type.setText(types[which]);
                                viewShowOrHide();
                                dialog.dismiss();
                            }
                        })
                        .create().show();
                break;
            case R.id.view_customer:
                if(customers == null) return;
                new QMUIDialog.MenuDialogBuilder(mContext)
                        .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                        .addItems(customers, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                        showToast("你选择了 " + types[which]);
                                text_customer.setText(customers[which]);
                                dialog.dismiss();
                            }
                        })
                        .create().show();
                break;
            case R.id.view_craft:
                if(craftList.getAllNames() == null) return;
                new QMUIDialog.MenuDialogBuilder(mContext)
                        .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                        .addItems(craftList.getAllNames(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                        showToast("你选择了 " + types[which]);
                                text_craft.setText(craftList.getAllNames()[which]);
                                craftCid = craftList.getList().get(which).getCid();
                                dialog.dismiss();
                            }
                        })
                        .create().show();
                break;
            case R.id.view_time:
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        if (calendar == null) {
                            calendar = Calendar.getInstance();
                        }
                        calendar.setTime(date);
                        onTimeChoosed();
                    }
                })
                        .addOnCancelClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .build();
                pvTime.show();
                ViewUtils.hideInput(mContext);
                break;
            case R.id.btn_add:
                if(TextUtils.isEmpty(edit_no.getText().toString())){
                    showToast("单号不能为空");
                    return;
                }
//                AddOrEditGoodsInfoActivity.toDetail(AddOrEditGoodsActivity.this,craftCid,Constants.SCANDATASULT);
                break;
            case R.id.btn_submit:   //提交前与叉车的秤重进行比对，超过预计重量时，通过蓝牙开启叉车报警
                if(text_type.getText().toString().equals("生产") ){
                    if(TextUtils.isEmpty(edit_gno.getText().toString())){
                        showToast("工单号不可为空");
                        return;
                    }
                }
                if(TextUtils.isEmpty(edit_no.getText().toString())){
                    showToast("单号不可为空");
                    return;
                }
                if(submitData.getWorks() == null || submitData.getWorks().size()<1){
                    showToast("请点击最下方入库资料按钮，添加子表");
                    return;
                }
                if(TextUtils.isEmpty(text_total.getText().toString())){
                    showToast("总数量不能为空");
                    return;
                }
//                if(MyUtils.getHomeSelectName().equals("加工入库") || switch_out.isChecked()){
                if(MyUtils.getHomeSelectName().equals("加工入库")){
                    btnsubmit();
                    return;
                }
                if (TextUtils.isEmpty(text_tooth_weight.getText().toString())) {
                    showToast("请先通过蓝牙获取重量");
                    return;
                }
                int checkStatus = submitData.toCheck(text_tooth_weight.getText().toString(),text_weight.getText().toString());
                switch (checkStatus){
                    case GoodsSubmitData.NOT_ENOUGH:
                        BluetoothUtils.getInstance().startWarning();
                        DialogUtils.DialogOne(mContext, "提示", "重量不足！", "知道了", new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                BluetoothUtils.getInstance().stopWarning();
                            }
                        });
                        break;
                    case GoodsSubmitData.CONTINUE:
                        btnsubmit();
                        break;
                    case GoodsSubmitData.OUT:
                        BluetoothUtils.getInstance().startWarning();
                        DialogUtils.DialogOne(mContext, "提示", "重量超重！", "知道了", new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                BluetoothUtils.getInstance().stopWarning(); //ice 叉车报警关闭
                            }
                        });
                        break;
                }
                break;
            case R.id.view_tooth_weight:
                if(!BluetoothUtils.getInstance().checkConnect()){
                    checkBlueTooth();
                    showToast("请点击右上角蓝牙按钮，匹配相关设备");
                    return;
                }
                BluetoothUtils.getInstance().sendAndNotify(Analysis.getBytes("R"), new BluetoothUtils.MySendListener() {
                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }

                    @Override
                    public void onSuccess(String result) {
//                String a ="+  0.081 kg";
                        String a =result;
                        String unit =  UnitUtil.getUnitByString(a);
                        workm.setWun(unit);
                        String weight = UnitUtil.getNumByString(a);

//                        double cz = UnitUtil.getRatio(unit,"g")/1000.0f;
//                        weight = MathUtils.multiply(weight,String.valueOf(cz));
                        text_tooth_weight.setText(weight);

                    }

                    public void onTimeout() {
                        showToast("超时");

                    }
                });
                break;
            case R.id.view_price:
                if(unitListBean == null) return;
                new QMUIDialog.MenuDialogBuilder(mContext)
                        .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                        .addItems(unitListBean.getAllUnits(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                text_unit.setText(unitListBean.getAllUnits()[which]);
                                dialog.dismiss();
                            }
                        })
                        .create().show();
                break;
            case R.id.view_good_name:
                if(TextUtils.isEmpty(edit_no.getText().toString())){
                    showToast("单号不能为空");
                    return;
                }
                ActivityTool.skipActivityForResult(mContext,GoodsDataActivity.class,Constants.GOODSDATARESULT);
                break;
            case R.id.view_location:
                new QMUIDialog.MenuDialogBuilder(mContext)
                        .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                        .addItems(locationListBean.getAllLocation(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                text_location.setText(locationListBean.getAllLocation()[which]);
                                dialog.dismiss();
                            }
                        })
                        .create().show();
                break;

        }

    }


    void onTimeChoosed() {
        text_time.setText(calendar == null? "": TimeUtils.getTimeByDate(calendar.getTime(), "yyyy-MM-dd"));
    }

    void btnsubmit(){
        if(edit_gno.getText().toString().isEmpty() && !text_craft.getText().toString().equals("期初")) {
            showToast("请扫描工单号");
        } else {
            workm.setAid(LoginBean.getInstance().getAcode());
            workm.setBfs(MyUtils.getHomeSelectId());
            workm.setUno(LoginBean.getInstance().getUname());
            if (text_type.getText().toString().equals("生产")) {
                workm.setCna(text_craft.getText().toString());
            }
            workm.setCid(craftCid);
            workm.setMdt(text_time.getText().toString());
            if (title.equals("修改")) {
                workm.setMid(workListData.getMid());        //新增不用
            }
            workm.setWno(edit_gno.getText().toString());
            workm.setMty(text_type.getText().toString());
            workm.setMno(edit_no.getText().toString());
            workm.setLoc(text_location.getText().toString());

            if (MyUtils.getHomeSelectName().equals("加工入库")) {
                workm.setMna(text_customer.getText().toString());
            } else {
                workm.setWch(text_tooth_weight.getText().toString());
            }

//            workm.setMfs(switch_out.isChecked()?1:0);

            submitData.setWorkm(workm);
            submitData.setWorksLoc(text_location.getText().toString());

            MyParams params = new MyParams();
            showProgress();
            Gson gson = new Gson();
            String a = gson.toJson(submitData);
            params.putJson(a);

            MyHttpUtils.postJson(Constants.URL_WORK_INSERT, params, new MyHttpListener() {
                        @Override
                        public void onSuccess(int httpWhat, Object result) {
                            if (isFinishing()) return;
                            BasisBean basisBean = (BasisBean) result;
                            showToast(((BasisBean) result).getStatusInfo());
                            setResult(GoodsListActivity.WARNLISTRESULT);

                            finish();
                        }

                        @Override
                        public void onFailure(int httpWhat, Object result) {
                            if (isFinishing()) return;
                            dismissProgress();
//                            super.onFailure(httpWhat, result);
                            if(result != null){
                                DialogUtils.showErrorDialog(mContext,((BasisBean) result).getStatusInfo());
                            }

                        }

                        @Override
                        public void onFinish(int httpWhat) {
                            dismissProgress();
                        }
                    },
                    0, BasisBean.class);
        }

    }


    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mAdapter.notifyDataSetChanged();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        initDataByWorks();
    }


    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.goods_info_list_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return submitData == null ? 0 : submitData.getWorks().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_code)
            public TextView text_code;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_specs)
            public TextView text_specs;
            @BindView(R.id.text_price)
            public TextView text_price;
            @BindView(R.id.text_num)
            public TextView text_num;
            @BindView(R.id.text_weight)
            public TextView text_weight;
            @BindView(R.id.text_kw)
            public TextView text_kw;
            @BindView(R.id.text_qrcode)
            public TextView text_qrcode;
            @BindView(R.id.btn_delete)
            public TextView btn_delete;
            @BindView(R.id.btn_edit)
            public TextView btn_edit;
            @BindView(R.id.view_part)
            public View view_part;
            @BindView(R.id.view_arrow)
            public View view_arrow;
            @BindView(R.id.text_gcd)
            public TextView text_gcd;
            @BindView(R.id.img_arrow)
            public ImageView img_arrow;
            @BindView(R.id.text_title)
            public TextView text_title;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {

                //之后加倒叙排列
                GoodsWorks data = submitData.getWorks().get(position);
                text_title.setText((position+1)+":  "+ data.getRfid()+"  "+ data.getGcd()+"  "+ data.getGna()+"  "+data.getGsp());
                text_code.setText(data.getGno());
                text_name.setText(data.getGna());
                text_specs.setText(data.getGsp());
                text_price.setText(""+data.getGun());
                text_num.setText(data.getGnu());
                text_weight.setText(""+data.getGwt());
                text_kw.setText(data.getWms());
                text_qrcode.setText(data.getRfid());
                text_gcd.setText(data.getGcd());
                if(data.isShowPart()){
                    img_arrow.setImageResource(R.drawable.home_app_icon_arrow_up);
                    view_part.setVisibility(View.VISIBLE);
                }else {
                    img_arrow.setImageResource(R.drawable.base_icon_arrow_down);
                    view_part.setVisibility(View.GONE);
                }
                view_arrow.setTag(position);
                btn_delete.setTag(position);
                btn_edit.setTag(position);
            }

            @OnClick(R.id.btn_delete)
            public void onItemDelClick(View v) {
                int position = (int) v.getTag();
                List<GoodsWorks> a = submitData.getWorks();
                a.remove(position);
                setListView();
            }
            @OnClick(R.id.btn_edit)
            public void onItemEditClick(View v) {
                //编辑工单
                int position = (int) v.getTag();
                GoodsWorks goodsWork = submitData.getWorks().get(position);
                if(TextUtils.isEmpty(edit_no.getText().toString())){
                    showToast("工单不可为空");
                    return;
                }

                switch (MyUtils.getHomeSelectName()) {
                    case "加工入库":
                        AddOrEditGoodsInfoActivity.toEdit(AddOrEditGoodsActivity.this,goodsWork,Constants.SCANDATASULT);
                        break;
                    default:
                        AddOrEditGoodsInfoActivity.toEdit(AddOrEditGoodsActivity.this,goodsWork.getRfid(),Constants.SCANDATASULT);
                        break;
                }

                }

            @OnClick(R.id.view_arrow)
            public void onItemArrowClick(View v) {
                //编辑工单
                int position = (int) v.getTag();
                GoodsWorks goodsWork = submitData.getWorks().get(position);
                goodsWork.setShowPart(!goodsWork.isShowPart());
                notifyItemChanged(getAdapterPosition());
            }



        }
    }

    GoodsListData goodsData = null;  //货品资料
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.SCANDATASULT){
            ArrayList<GoodsWorks> worksList = (ArrayList<GoodsWorks>) data.getSerializableExtra("list");
            submitListAddBean(worksList);
        }

        if(resultCode == Constants.GOODSDATARESULT){
            goodsData = (GoodsListData) data.getSerializableExtra("data");
            MyUtils.setNotNullText(text_good_name,goodsData.getGna());
        }
    }

    private void submitListAddBean(ArrayList<GoodsWorks> worksList){
        if(submitData.getWorks() == null || submitData.getWorks().size()<0){
            submitData.setWorks(worksList);
        }else {
            if(worksList != null){
                for (GoodsWorks childBean : worksList){
                    boolean isHave = false;
                    for(int i = 0;i<submitData.getWorks().size();i++){
                        GoodsWorks paramBean = submitData.getWorks().get(i);
                        if(childBean.getRfid().equals(paramBean.getRfid())){
                            submitData.getWorks().set(i,childBean);
                            isHave = true;
                        }
                    }
                    if(!isHave){
                        submitData.getWorks().add(childBean);
                    }
                }
            }
        }
        mRecyclerView.setVisibility(View.VISIBLE);
        setListView();
    }

    void checkBlueTooth(){
        int blueToothIcon = BluetoothUtils.getInstance().checkConnect()?R.mipmap.blue_tooth_on:R.mipmap.blue_tooth_off;
        setTitleRightButton(blueToothIcon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!BluetoothUtils.getInstance().checkConnect()){
                    ActivityTool.skipActivity(mContext, SearchBlueToothActivity.class);
                }
//                else {
//                    BluetoothUtils.getInstance().logout();
//                    checkBlueTooth();
//                }
            }
        });
    }

    void viewShowOrHide(){
        switch (text_type.getText().toString()){
            case "生产":
                view_scan.setVisibility(View.VISIBLE);
                break;
            case "订单":
                view_scan.setVisibility(View.VISIBLE);
                if(customerListbean.getAllCustomerNames() != null){
                    customers = customerListbean.getAllCustomerNames();
                    MyUtils.setNotNullText(text_customer,customers[0]);
                }
                break;
            case "计划":
                view_scan.setVisibility(View.VISIBLE);
                customers = getResources().getStringArray(R.array.no_customer);
                text_customer.setText(customers[0]);
                break;
            default:
                view_scan.setVisibility(View.GONE);
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        ReceiverUtils.registerUHFAndScannerReceiver(mContext,mResultReceiver);
        checkBlueTooth();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReceiverUtils.unRegisterReceiver(mContext,mResultReceiver);
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void onEventGet(MyEvent event) {
        checkBlueTooth();
        if (event.getType() == MyEvent.EVENT_TYPE_DISCONNECT) {
            BluetoothUtils.getInstance().showReconnectDialog(mContext);
        }else if (event.getType() == MyEvent.EVENT_TYPE_CONNECT) {
            checkBlueTooth();
        }
    }
}
